// pages/products/products_flex.js
var app = getApp();
var currentShopId = 0;
var currentPage = 1;
var interval;
Page({
    data: {
        hideCartAS: true,
        total: 0,
        cart_count: 0,
        categories_actice: -1,
        categories: [],
        products: [],
        carts: [],
        curProduct: {},
        showModal: false,
        loadMore: true,
        showContact: false,
        closeNotify: false,
        direction: 'left',
        distance: 0,
        pace: 1.5,
        notifyTextlen: 0,
        curSpecIndex: 0,
        curProductId: 0,
        choose_num: 1
    },
    onLoad: function (options) {
        // 页面初始化 获取店铺id
        this.setData({
            windowHeight: app.systemInfo.windowHeight
        })
        if (options.shop_id > 0) {
            currentShopId = options.shop_id;
            wx.setStorageSync('shop_id', options.shop_id);
        } else {
            currentShopId = wx.getStorageSync('shop_id');
        }

    },
    onHide:function(){
       clearInterval(interval);
    },
    onUnload:function(){
        clearInterval(interval);
    },
    onReady: function () {
        // 页面渲染完成
        var that = this;
        console.log("ready")
        if(!currentShopId){
            currentShopId = wx.getStorageSync('shop_id');
        }
        

        currentPage = 1;
        if (!currentShopId) {
            wx.showModal({
                title: '提示',
                showCancel: false,
                content: '暂无当前店铺，请从浏览记录中选择店铺',
                confirmText: '立即前往',
                success: function (res) {
                    if (res.confirm) {
                        wx.redirectTo({
                            url: '/pages/index/history'
                        });
                    }
                }
            })
            return
        }

        //读取分类列表
        app.func.req('product_cates/index', { shop_id: currentShopId }, 'GET', function (res) {
            var index = that.data.categories_actice;
            var cateId = 0;
            var categories = app.util.covertProductCates(res.result);
         //   categories[0].active = true;
            if (that.data.categories.length > 0) {
                var oldCategories = that.data.categories;
                var oldCateId = oldCategories[index].id;

                for (var i = 0; i < categories.length; i++) {
                    if (categories[i].id == oldCateId) {
                        categories[i].active = true;
                        cateId = oldCateId;
                    } else {
                        categories[i].active = false;
                    }
                }
            }
            that.setData({
                goodsall:true,
                categories: categories,
                products: []
            });
            // 获取该分类下的商品列表
            that.getproducts(cateId);
        });

        app.func.req('shops/show', {
            id: currentShopId
        }, 'GET', function (res) {
            that.setData({
                shop: res.result
            },function(){
                if (that.data.shop.announcement != "") {
                    wx.createSelectorQuery().select('.notify_text').boundingClientRect(function (rect) {
                        that.setData({
                            notifyTextlen: rect.width
                        }, function () {
                            that.runText();
                        })
                    }).exec();
                }  
            });
  
            var title = '店铺首页';
            if (res.result.name) {
                title = res.result.name;
            }
            wx.setNavigationBarTitle({
                title: title
            });

        }, {
                'token': wx.getStorageSync('token')
            });
    },
    onShow: function () {
        var carts = wx.getStorageSync('carts');
        var cart_count = 0;
        var that = this;
        if (carts) {
            carts.forEach(function (cart) {
                if (cart.shopId == currentShopId) {
                    cart_count = cart.products.length;
                }
            })
        }
        this.setData({ cart_count: cart_count })
        wx.createSelectorQuery().select('.notify_text').boundingClientRect(function (rect) {
            if(rect){
                that.setData({
                    notifyTextlen: rect.width
                }, function () {
                    that.runText();
                })
            }
           
        }).exec();


    },
    runText() {

        var that = this;
        var notifyBoxLen = wx.getSystemInfoSync().windowWidth * 0.8;
        var notifyTextlen = this.data.notifyTextlen;
        interval = setInterval(function () {
            if (-that.data.distance <= notifyTextlen) {
                that.setData({
                    distance: that.data.distance - that.data.pace
                })
            }
            else {
                clearInterval(interval);
                that.setData({
                    distance: notifyBoxLen + wx.getSystemInfoSync().windowWidth * 0.1
                })
                that.runText();
            }
        }, 20);

    },
    addCart:function(e){
        var that =this;
        this.setData({
            showModal: true,
            curProductId: e.currentTarget.dataset.id
        })
        app.func.req('products/show', {
            id: that.data.curProductId,
            shop_id: that.data.shop.id
        }, 'GET', function (res) {
            console.log(res.result)
            res.result.specs = res.result.spec;
            delete res.result.spec;
            console.log(res.result)
            if(res.result.specs.length==0)
                res.result.num=1;
            else 
                res.result.specs.map(function(el){
                    el.num=1;
                })
                
            that.setData({
                curProduct: res.result
            })
            
        }, {
            'token': wx.getStorageSync('token')
        })
    },
    to_cart(){
        var carts = wx.getStorageSync('carts');
        var that =this;
        if(carts.length==0)
            carts = []; 
        var product = this.data.curProduct;
        console.log(product)
        console.log(carts)
        var cart = {
            shopId: currentShopId,
            products: [product]
        };
        if (!carts) {
            carts = [cart]
        }
        var isset_cart = false;
        for (var i = 0; i < carts.length; i++) {
            if (carts[i].shopId == currentShopId) {
                cart = carts[i];
                isset_cart = true;
            }
        }
        var isset_product = false;
        for (var j = 0; j < cart.products.length; j++) {
            if (cart.products[j].id == this.data.curProductId) {
                product = cart.products[j];
                isset_product = true;
              /*  var arr = cart.products[j];
                arr.specs.splice(0, this.data.curSpecIndex);
                arr.specs.splice(1, arr.specs.length-1);
                console.log(arr)
                 product = arr;    */
            }          
        }
       
        if (product.specs.length == 0) {
            product.num = this.data.curProduct.num;
        } else {
            console.log(product)
            console.log(this.data.curProduct)
            product.specs[this.data.curSpecIndex].num = this.data.curProduct.specs[this.data.curSpecIndex].num;
            //product.specs = product.specs[this.data.curSpecIndex];
        }
        if (!isset_product && product.specs.length > 0) {
            var arr = product;
           /* arr.specs.splice(0, that.data.curSpecIndex);
            arr.specs.splice(1, arr.specs.length - 1); */
            console.log(that.data.curSpecIndex)
            console.log(arr)
            arr.specs.forEach(function(el,i){
                if(i!==that.data.curSpecIndex){
                    el.num = 0;
                }
            })
            product = arr;
        }
        if (!isset_cart ) {
            carts.push(cart)
        } else if (isset_cart && !isset_product) {
            cart.products.push(product)
        }
        console.log(carts)
        wx.setStorage({
            key: 'carts',
            data: carts,
        })
       
        this.closeModal()
    },
    close_modal:function(){
        this.closeModal();
    },
    closeModal: function () {
        this.setData({
            showModal: false
        })   
    },
    //获取当前当前店铺指定分类下的商品列表
    getproducts: function (cateId) {
        console.log("currentPage:" + currentPage);
        var that = this;
        that.setData({
            loadMore: false
        })
        wx.showLoading({ title: '数据加载中...', mask: true });
        app.func.req('products/index', {
            shop_id: currentShopId,
            product_cate_id: cateId,
            page_index: currentPage,
            page_size: 10
        }, 'GET', function (res) {
            console.log(res)
            if (res.code == "success") {
                var products = res.result;
                var currentProducts = that.data.products.concat(products);
                that.setData({
                    loadMore: true
                });
                //购物车信息加到商品中
              
                for(var i in currentProducts){
                    var specs = currentProducts[i].specs;
                    if(specs.length){
                        var price = 0;
                        for(var v=0;v<specs.length;v++)
                        {
                            price +=parseInt(specs[v].stock);
                            
                        }
                        
                        currentProducts[i].product_num = price;                     
                    }
                        

                
                }
                that.setData({
                    products: currentProducts
                })
                currentPage++;
                wx.hideLoading();
            } else {
                wx.hideLoading();
            }

        }, {
                'token': wx.getStorageSync('token')
            });
    },
    loadMore: function () {
        var that = this;
        if (that.data.loadMore) {
            if(that.data.categories_actice==-1){
                that.getproducts(0); 
            }else{
                that.getproducts(that.data.categories[that.data.categories_actice].id); 
            }
           
        }
    },
    // 规格切换
    toggleSpec: function (e) {
        var that = this;
        var index = e.target.dataset.index;
        this.setData({
            curSpecIndex: index
        })
        console.log(this.data.curSpecIndex)
        
    },
    //分类切换
    categorySelect: function (e) {
        var that = this;
        var offsetLeft = e.currentTarget.offsetLeft;
        that.setData({
            scrollNavbarLeft:offsetLeft -85
        });
        var index = e.target.dataset.index;
        var new_categories = this.data.categories;
        var old_active = this.data.categories_actice;
        var new_active = index;
 
        if(index=='-1'){
            new_categories.forEach(function(item,index,array){
                new_categories[index]['active']= false;
            })
            this.setData({
                goodsall:true,
                categories: new_categories,
                categories_actice: new_active,
                products: []
            })
            //获取商品列表
            currentPage = 1;
            that.getproducts(0);
            return;
        }else{
            if(old_active>=0){
                new_categories[old_active].active = false;
            }
        }

        new_categories[index].active = true;
        that.setData({
            goodsall:false,
            categories: new_categories,
            categories_actice: new_active,
            products: []
        })
        //获取商品列表
        currentPage = 1;
        that.getproducts(new_categories[index].id);
    },
    closeModal: function () {
        this.setData({
            showModal: false
        })
    },
    onShareAppMessage: function () {
        var nickname = wx.getStorageSync('nickname');
        if (!nickname) {
            nickname = ''
        }

        return {
            title: nickname + '分享了' + this.data.shop.name,
            imageUrl: this.data.product.logo.replace(/(^\s*)|(\s*$)/g, ""),
            path: 'pages/share/share?shop_id=' + currentShopId + '&&products_share=true'
        }
    },
    showContact: function () {
        this.setData({
            showContact: true
        })
    },
    cartMinus: function (e) {
        var that = this;
        var specIndex = this.data.curSpecIndex;
        console.log(e)
        var curProduct = this.data.curProduct;
        console.log(curProduct)
        if (curProduct.specs.length == 0) {
            if (curProduct.num > 1) {
                curProduct.num--;
                that.setData({
                    minusSrc: "/images/can-minus.png",
                    plusSrc: "/images/can-plus.png"
                })
            } else {
                curProduct.num == 0;
                that.setData({
                    minusSrc: "/images/cannot-minus.png",
                    plusSrc: "/images/can-plus.png"
                })
            }
        } else if (curProduct.specs.length > 0) {
            console.log(specIndex)
            if (curProduct.specs[specIndex].num > 1) {
                curProduct.specs[specIndex].num--;
                that.setData({
                    minusSrc: "/images/can-minus.png",
                    plusSrc: "/images/can-plus.png"
                })
            } else {
                curProduct.specs[specIndex].num == 1;
                that.setData({
                    minusSrc: "/images/cannot-minus.png",
                    plusSrc: "/images/can-plus.png"
                })
            }
        }
        that.setData({
            curProduct: curProduct
        })
    },
    cartPlus: function (e) {
        var that = this;
        var specIndex = this.data.curSpecIndex;
        var curProduct = this.data.curProduct;

        if (curProduct.specs.length == 0) {
            if (curProduct.is_limit > 0 && curProduct.limit_num < curProduct.num + 1) {
                wx.showToast({
                    title: '限购' + curProduct.is_limit + '个',
                    image: '/images/fail.png',
                    duration: 2000
                });
                that.setData({
                    minusSrc: "/images/can-minus.png",
                    plusSrc: '/images/cannot-plus.png'
                })
            } else {
                curProduct.num++;

                that.setData({
                    minusSrc: "/images/can-minus.png",
                    plusSrc: "/images/can-plus.png"
                })
            }
        } else if (curProduct.specs.length > 0) {
            if (curProduct.is_limit > 0 && curProduct.specs[specIndex].limit_num < curProduct.specs[specIndex].num + 1) {
                wx.showToast({
                    title: '限购' + curProduct.is_limit + '个',
                    image: '/images/fail.png',
                    duration: 2000
                });
                that.setData({
                    minusSrc: "/images/can-minus.png",
                    plusSrc: "/images/cannot-plus.png"
                })
            } else {
                curProduct.specs[specIndex].num++;
                that.setData({
                    minusSrc: "/images/can-minus.png",
                    plusSrc: "/images/can-plus.png"
                })
            }
        }

        that.setData({
            curProduct: curProduct
        })
        console.log(this.data.curProduct)
    },
    closeContact: function () {
        this.setData({
            showContact: false
        })
    },
    closeNotify: function () {
        this.setData({
            closeNotify: true
        })
    },
    telPhone: function () {
        var that = this;
        var shop = that.data.shop;
        var phone = shop.kfphone ? shop.kfphone : shop.phone;
        wx.makePhoneCall({
            phoneNumber: phone
        })
    },
    copyWechat: function () {
        var that = this;
        wx.setClipboardData({
            data: that.data.shop.wechat,
            success: function (res) {
                wx.showToast({
                    title: '复制成功！',
                    icon: 'success',
                    duration: 2000,
                    mask: true
                })
            }
        });
    }
})
